package com.example.demo.phone.util;

import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.StringUtils;

import java.util.Iterator;
import java.util.Map;
import java.util.Objects;

public class UrlUtil {

    private static final String EMPTY_RESULT = "";
    private static final String QUESTION_MARK = "?";
    private static final String AND = "&";
    private static final String EQUAL = "=";

    public static String createUrl(String url, Iterator<Map.Entry<String, Object>> uriParams) {
        if (StringUtils.isBlank(url) || Objects.isNull(uriParams) || !uriParams.hasNext()) {
            return url;
        }

        Map.Entry<String, Object> first = uriParams.next();
        StringBuilder result = new StringBuilder(url);

        //看看是不是有?了。
        int markIndex = StringUtils.indexOf(url, QUESTION_MARK);
        if (markIndex == StringUtils.INDEX_NOT_FOUND) {
            result.append(QUESTION_MARK);
        } else if (url.length() > markIndex + 1) {
            result.append(AND);
        }

        result.append(first.getKey())
                .append(EQUAL).append(first.getValue());

        //没有下一个就直接组装第一个返回
        if (!uriParams.hasNext()) {
            return result.toString();
        }

        uriParams.forEachRemaining(entry -> result.append(AND).append(entry.getKey())
                                            .append(EQUAL).append(entry.getValue()));
        return result.toString();
    }

    public static String createUrl(String url, Map<String, Object> uriParams) {
        return MapUtils.isEmpty(uriParams) ? url : UrlUtil.createUrl(url, uriParams.entrySet().iterator());
    }

}
